<?php
/**
 * Created by PhpStorm.
 * User: Digvijay
 * Date: 9/20/14
 * Time: 3:49 PM
 */

class Orders extends MY_Controller {

    function newOrders() {
        $locations = $this->findAll("Branch");
        foreach ($locations as $location) {
            $location->setAddress("");
        }
        $data = array("pageTitle" => "New Orders", "locations" => $locations);
        $this->load->view("admin/order-new", $data);
    }

    function cancelOrders() {
        $data = array("pageTitle" => "Canceled Orders");
        $this->load->view("admin/order-cancel", $data);
    }

    function completedOrders() {
        $data = array("pageTitle" => "Completed Orders");
        $this->load->view("admin/order-complete", $data);
    }

    function getOrders($type = null) {
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $response = new Response();
        try {
            if ($type == null) {
                throw new RuntimeException("Invalid Request");
            }
            $orderType = null;
            if ($type == "NEW") {
                $orderType = Order::ORDER_PENDING;
            } else if ($type == "CANCEL") {
                $orderType = Order::ORDER_CANCELLED;
            } else if ($type = "COMPLETE") {
                $orderType = Order::ORDER_DELIVERED;
            }

            $orders = $this->findAllOrdersByType($orderType);
            $response->setData($orders);
        } catch (Exception $e) {
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
        }
        header('Content-Type: application/json');
        echo json_encode($response, JSON_PRETTY_PRINT);
    }

    function getOrderDetails($id = null) {
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $response = new Response();
        try {
            if ($id == null) {
                throw new RuntimeException("Invalid Request, Please Try Again.");
            }
            $order = $this->findById("Order", $id);
            $order->setOrderItems($order->getOrderItems()->toArray());
            $response->setData($order);
        } catch (Exception $e) {
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
        }
        header('Content-Type: application/json');
        echo json_encode($response, JSON_PRETTY_PRINT);
    }

    function updateOrderItem($id = null, $quantity = null, $discount = null, $location = null, $orderId = null) {
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $response = new Response();
        try {
            if ($id == null || $quantity == null || $discount == null || $location == null || $orderId == null) {
                throw new RuntimeException("Invalid Request, Please Try Again.");
            }
            $item = $this->findById("OrderItem", $id);
            $branch = $this->findById("Branch", $location);
            $product = $item->getProduct();
            if ($product != null) {
                $originalQuantity = $item->getQuantity();
                $originalBranch = $item->getBranch();

                if ($branch->getId() != $item->getBranch()->getId()) {
                    if ($product->getProductActualStockByLocation($branch) >= $quantity) {
                        $item->setQuantity($quantity);
                        $item->setBranch($branch);

                        $product->addProductStockByBranch($originalBranch, $originalQuantity);
                        $product->updateProductStockByBranch($branch, $quantity);
                        $this->save($product);
                    }
                } else {
                    if ($originalQuantity != $quantity) {
                        $item->setQuantity($quantity);
                        if ($originalQuantity < $quantity) {
                            if ($product->getProductActualStockByLocation($branch) >= $quantity - $originalQuantity) {
                                $product->updateProductStockByBranch($originalBranch, $quantity - $originalQuantity);
                            }
                        } else {
                            $product->addProductStockByBranch($originalBranch, $originalQuantity - $quantity);
                        }
                        $this->save($product);
                    }
                }
                $item->setDiscount($discount);
                $this->save($item);
            }
            $order = $this->findById("Order", $orderId);
            $subTotal = 0;
            foreach ($order->getOrderItems() as $itm) {
                $totalItemPrice = $itm->getQuantity() * $itm->getPrice();
                $discount = $itm->getDiscount();
                if ($discount != null && $discount > 0) {
                    $subTotal += $totalItemPrice - ($totalItemPrice * ($discount / 100));
                } else {
                    $subTotal += $totalItemPrice;
                }
            }
            $order->setPrice($subTotal);
            $this->save($order);
            $order->setOrderItems($order->getOrderItems()->toArray());
            $response->setData(array("order" => $order));
        } catch (Exception $e) {
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
        }
        header('Content-Type: application/json');
        echo json_encode($response, JSON_PRETTY_PRINT);
    }

    function deleteOrderItem($id = null, $orderId = null) {
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $response = new Response();
        try {
            if ($id == null || $orderId == null) {
                throw new RuntimeException("Invalid Request, Please Try Again.");
            }
            $item = $this->findById("OrderItem", $id);
            $product = $item->getProduct();
            if ($product == null) {
                throw new RuntimeException("Product Not Found");
            }

            $originalQuantity = $item->getQuantity();
            $originalBranch = $item->getBranch();
            $product->addProductStockByBranch($originalBranch, $originalQuantity);
            $this->save($product);

            $order = $this->findById("Order", $orderId);
            $subTotal = 0;
            $orderItems = $order->getOrderItems();
            foreach ($orderItems as $itm) {
                if ($itm->getId() == $id) {
                    $order->removeItem($itm);
                    continue;
                }
                $totalItemPrice = $itm->getQuantity() * $itm->getPrice();
                $discount = $itm->getDiscount();
                if ($discount != null && $discount > 0) {
                    $subTotal += $totalItemPrice - ($totalItemPrice * ($discount / 100));
                } else {
                    $subTotal += $totalItemPrice;
                }
            }
            $order->setPrice($subTotal);
            $this->save($order);
            $order->setOrderItems($order->getOrderItems()->toArray());
            $response->setData(array("order" => $order));
        } catch (Exception $e) {
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
        }
        header('Content-Type: application/json');
        echo json_encode($response, JSON_PRETTY_PRINT);
    }

    function orderComplete($id = null) {
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $response = new Response();
        try {
            if ($id == null) {
                throw new RuntimeException("Invalid Request, Please try again.");
            }
            $order = $this->findById("Order", $id);
            foreach ($order->getOrderItems() as $itm) {
                $product = $itm->getProduct();
                $product->updateProductTotalStock($itm->getBranch(), $itm->getQuantity());
                $this->save($product);
            }
            $order->setStatus(Order::ORDER_DELIVERED);
            $this->save($order);
            $response->setData(true);
        } catch (Exception $e) {
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
        }
        header('Content-Type: application/json');
        echo json_encode($response, JSON_PRETTY_PRINT);
    }

    function orderCancel($id = null) {
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $response = new Response();
        try {
            if ($id == null) {
                throw new RuntimeException("Invalid Request, Please try again.");
            }
            $branchEmail = "";
            $order = $this->findById("Order", $id);
            foreach ($order->getOrderItems() as $itm) {
                $product = $itm->getProduct();
                $product->addProductStockByBranch($itm->getBranch(), $itm->getQuantity());
                $this->save($product);

                $branchEmail = $itm->getBranch()->getEmail();
            }
            $order->setStatus(Order::ORDER_CANCELLED);
            $this->save($order);
            $response->setData(true);
            try{
                $notification = $this->findById("Notification", 1);
                $agent = $order->getAgency();
                $emailData = array("client"=>$agent, "order"=>$order);
                $this->sendOrderCancelNotificationMail($agent->getEmail(),"Order Canceled :".$order->getId(), $emailData);
                $this->sendOrderCancelNotificationMail($branchEmail,"Order Canceled ".$order->getId(), $emailData);
                $this->sendOrderCancelNotificationMail($notification->getOrderPlaceEmail(),"Order Canceled ".$order->getId(), $emailData);
            }catch (Exception $ex){

            }

        } catch (Exception $e) {
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
        }
        header('Content-Type: application/json');
        echo json_encode($response, JSON_PRETTY_PRINT);
    }

    function getAgencyDetails($orderId) {
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $response = new Response();
        try {
            if ($orderId == null) {
                throw new RuntimeException("Invalid Request, Please try again.");
            }
            $order = $this->findById("Order", $orderId);
            $agency = $order->getAgency();
            $response->setData($agency);
        } catch (Exception $e) {
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
        }
        header('Content-Type: application/json');
        echo json_encode($response, JSON_PRETTY_PRINT);
    }

    function mail(){
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $response = new Response();
        try {
            $email = $this->input->post("emailto");
            $subject = $this->input->post("subject");
            $message = $this->input->post("message");

            $arr = array("sent" => false);
            if($this->sendMail($email,$subject,$message)){
                $arr["sent"] = true;
            }
            $response->setData($arr);
        } catch (Exception $e) {
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
        }
        header('Content-Type: application/json');
        echo json_encode($response, JSON_PRETTY_PRINT);
    }
} 